package cn.exrick.manager.controller;


import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.common.utils.ThreadPoolUtil;
import cn.exrick.manager.pojo.TbEmailTemplate;
import cn.exrick.manager.pojo.TbItem;
import cn.exrick.manager.pojo.TbUser;
import cn.exrick.manager.service.EmailTemplateService;
import cn.exrick.manager.service.ItemService;
import cn.exrick.manager.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@Api(description = "商品列表信息")
public class ItemController{

    private final static Logger log= LoggerFactory.getLogger(ItemController.class);

    @Autowired
    private ItemService itemService;
   /* @Autowired
    private SearchItemService searchItemService;*/
    @Autowired
    private UserService userService;
    @Autowired
    private EmailTemplateService emailTemplateService;
    @Value("${IMAGE_ACCESS_URL}")
    private String imageUrl;
    @Value("${FILE_STORE_PATH}")
    private String storePath;

    @RequestMapping(value = "/item/{itemId}",method = RequestMethod.GET)
    @ApiOperation(value = "通过ID获取商品")
    public Result<TbItem> getItemById(@PathVariable Long itemId){

        TbItem tbItem=itemService.getItemById(itemId);
        String image = tbItem.getImage();
        image = image.replace(imageUrl,"");

        String cover;
        if(image.contains(",")){
            cover = image.substring(0,image.indexOf(","));
            tbItem.setCover(imageUrl + cover);
            tbItem.setImage(image.substring(image.indexOf(",") + 1));
        }else{
            cover = image;
            tbItem.setCover(imageUrl + cover);
            tbItem.setImage(image);
        }

        File file = new File(storePath + "/" + cover);
        byte[] bytes;
        String coverBase64 = null;
        try {
            bytes = FileUtils.readFileToByteArray(file);
            coverBase64 = Base64Utils.encodeToString(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            coverBase64 = null;
        }

        tbItem.setCoverBase64(coverBase64);
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    @RequestMapping(value = "/item/view/{itemId}",method = RequestMethod.GET)
    public Result<TbItem> view(@PathVariable Long itemId){
        TbItem tbItem=itemService.getItemById(itemId);
        String image = tbItem.getImage();
        if(image.contains(",")){
            tbItem.setCover(image.substring(0,image.indexOf(",")));
            tbItem.setImage(image.substring(image.indexOf(",") + 1));
        }else{
            tbItem.setCover(image);
            tbItem.setImage(image);
        }
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    @RequestMapping(value = "/item/list",method = RequestMethod.GET)
    @ApiOperation(value = "分页搜索排序获取商品列表")
    public DataTablesResult getItemList(int draw, int start, int length, int cid,String recommend, @RequestParam("search[value]") String search,
                                        @RequestParam("order[0][column]") int orderCol, @RequestParam("order[0][dir]") String orderDir,
                                        String status, String minDate, String maxDate){


        //获取客户端需要排序的列
        String[] cols = {"checkbox", "image", "title",  "tag", "price", "num", "sale_date","is_recommend","status"};
        String orderColumn = cols[orderCol];
        if(orderColumn == null) {
            orderColumn = "sale_date";
        }
        //获取排序方式 默认为desc(asc)
        if(orderDir == null) {
            orderDir = "desc";
        }
        DataTablesResult result=itemService.getItemList(draw,start,length,cid,recommend,search,status,minDate,maxDate,orderColumn,orderDir);
        return result;
    }

    @RequestMapping(value = "/item/listSearch",method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页搜索排序获取商品列表")
    public DataTablesResult getItemSearchList(int draw, int start, int length,int cid,String recommend,String searchKey,String status,String minDate,String maxDate,
                                              @RequestParam("search[value]") String search, @RequestParam("order[0][column]") int orderCol,
                                              @RequestParam("order[0][dir]") String orderDir){

        //获取客户端需要排序的列
        String[] cols = {"checkbox", "image", "title", "introduction", "tag", "price", "num", "sale_date","status"};
        //默认排序列
        String orderColumn = cols[orderCol];
        if(orderColumn == null) {
            orderColumn = "sale_date";
        }
        //获取排序方式 默认为desc(asc)
        if(orderDir == null) {
            orderDir = "desc";
        }
        if(!search.isEmpty()){
            searchKey=search;
        }
        DataTablesResult result=itemService.getItemSearchList(draw,start,length,cid,recommend,searchKey,status,minDate,maxDate,orderColumn,orderDir);
        return result;
    }

    @RequestMapping(value = "/item/count",method = RequestMethod.GET)
    @ApiOperation(value = "获得商品总数目")
    public DataTablesResult getAllItemCount(String minDate,String maxDate,String status){

        DataTablesResult result=itemService.getAllItemCount(status,minDate,maxDate);
        return result;
    }

    @RequestMapping(value = "/item/stop/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "下架商品")
    public Result<TbItem> stopItem(@PathVariable Long id){

        TbItem tbItem = itemService.alertItemState(id, CommonConstant.ITEM_STATUS_REMOVE);
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    @RequestMapping(value = "/item/start/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "提交审批")
    public Result<TbItem> startItem(@PathVariable Long id){
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        TbItem tbItem = itemService.alertItemState(id,CommonConstant.ITEM_STATUS_APPROVAL);
        //发送审批通知
        ThreadPoolUtil.getPool().execute(()-> {
            sendApprovalEmail(tbItem.getTitle(),username);
        });
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    @RequestMapping(value = "/item/del/{ids}",method = RequestMethod.DELETE)
    @ApiOperation(value = "删除商品")
    public Result<TbItem> deleteItem(@PathVariable Long[] ids){
        boolean flag = itemService.checkItemHasRelatedOrder(Arrays.asList(ids));
        if(flag){
            return new ResultUtil<TbItem>().setErrorMsg("商品有关联的订单信息，不能删除！");
        }

        for(Long id:ids){
            itemService.deleteItem(id);
        }
        return new ResultUtil<TbItem>().setData(null);
    }

    private void sendApprovalEmail(String itemTitle,String username){
        try {
            List<TbUser> adminList = userService.getAllAdmin();
            if(CollectionUtils.isNotEmpty(adminList)){
                TbEmailTemplate emailTemplate = emailTemplateService.getTemplateByType(CommonConstant.EMAIL_REMIND_TYPE_APPROVAL_ITEM);
                String template = emailTemplate.getTemplate();
                if(template.contains("${提交审批人名称}")){
                    template = template.replace("${提交审批人名称}",username);
                }
                if(template.contains("${商品名称}")){
                    template = template.replace("${商品名称}",itemTitle);
                }

                for(TbUser tbUser : adminList){
                    String content = template;
                    if(content.contains("${收件人名称}")){
                        content = content.replace("${收件人名称}",tbUser.getUsername());
                    }

                    if(StringUtils.isNotBlank(tbUser.getEmail())){
                        emailTemplateService.sendEmail("纪念品商城新增商品审批通知",tbUser.getEmail(),content);
                        log.info("发送了商品审批通知邮件给"+tbUser.getUsername());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/item/add",method = RequestMethod.POST)
    @ApiOperation(value = "添加商品")
    public Result<TbItem> addItem(TbItem tbItem){
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        TbUser user = userService.getUserByUsername(username);
        tbItem.setCreateBy(user.getId());
        tbItem.setUpdateBy(user.getId());
        TbItem item=itemService.addItem(tbItem);
        //发送审批通知
        if(tbItem.getStatus() == CommonConstant.ITEM_STATUS_APPROVAL){
            ThreadPoolUtil.getPool().execute(()-> {
                sendApprovalEmail(tbItem.getTitle(),username);
            });
        }
        return new ResultUtil<TbItem>().setData(item);
    }

    @RequestMapping(value = "/item/update/{id}",method = RequestMethod.POST)
    @ApiOperation(value = "编辑商品")
    public Result<TbItem> updateItem(@PathVariable Long id, TbItem tbItem){
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        TbUser user = userService.getUserByUsername(username);
        tbItem.setUpdateBy(user.getId());
        TbItem item=itemService.updateItem(id,tbItem);
        return new ResultUtil<TbItem>().setData(item);
    }

    @RequestMapping(value = "/item/pass/{id}",method = RequestMethod.POST)
    public Result<TbItem> passItem(@PathVariable Long id){

        TbItem tbItem = itemService.alertItemState(id, CommonConstant.ITEM_STATUS_RELAASE);
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    @RequestMapping(value = "/item/refuse/{id}",method = RequestMethod.POST)
    public Result<TbItem> refuseItem(@PathVariable Long id){

        TbItem tbItem = itemService.alertItemState(id,CommonConstant.ITEM_STATUS_REFUSE);
        return new ResultUtil<TbItem>().setData(tbItem);
    }

    /*@RequestMapping(value = "/item/importIndex",method = RequestMethod.GET)
    @ApiOperation(value = "导入商品索引至ES")
    public Result<Object> importIndex(){

        searchItemService.importAllItems();
        return new ResultUtil<Object>().setData(null);
    }*/

    /*@RequestMapping(value = "/es/getInfo",method = RequestMethod.GET)
    @ApiOperation(value = "获取ES信息")
    public Result<Object> getESInfo(){

        EsInfo esInfo=searchItemService.getEsInfo();
        return new ResultUtil<Object>().setData(esInfo);
    }*/

    @RequestMapping(value = "/item/recommend",method = RequestMethod.POST)
    public Result<Object> recommendItem(Long[] ids,int recommend){
        itemService.updateRecommendItem(Arrays.asList(ids),recommend);
        return new ResultUtil<Object>().setData(null);
    }

}
